package com.bzxhh.spring6.tx.service.impl;

import com.bzxhh.spring6.tx.dao.BookDao;
import com.bzxhh.spring6.tx.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Service
//@Transactional
//@Transactional(readOnly = true) //只读操作（只能查询）

//@Transactional(timeout = 3) //超时

//回滚策略
//@Transactional(noRollbackFor = ArithmeticException.class) //异常事务不回滚
//@Transactional(noRollbackForClassName = "java.lang.ArithmeticException")

//隔离级别
//@Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
//@Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
//@Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
//@Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
//@Transactional(isolation = Isolation.SERIALIZABLE)//串行化

//传播行为
//@Transactional(propagation = Propagation.REQUIRED)
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;

    @Override
    public void buyBook(Integer bookId, Integer userId) {
        //TODO 用于演示超时
//        try {
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        //查询图书的价格
        Integer price = bookDao.getPriceByBookId(bookId);
        //更新图书的库存
        bookDao.updateStock(bookId);
        //更新用户的余额
        bookDao.updateBalance(userId, price);

//        //TODO 演示此异常不回滚
//        System.out.println(1 / 0);
    }
}
